<template>
  <div class="container">
    <el-tag
      v-for="(time, index) in _timeRanges"
      :key="time"
      closable
      :disable-transitions="false"
      class="time-range-tag"
      @close="removeTimeFromTimes(index)"
    >
      {{ time }}
    </el-tag>
    <div v-if="inputTagVisible" class="time-range-tag time-picker-box">
      <el-time-picker
        v-model="inputTimeRange"
        format="HH:mm"
        value-format="HH:mm"
        is-range
        range-separator="-"
        start-placeholder="开始时间"
        end-placeholder="结束时间"
        size="small"
      />
    </div>
    <el-button v-if="inputTagVisible" class="time-range-tag button-new-tag" size="small" @click="() => addTime()"> √ 完成 </el-button>
    <el-button v-else class="time-range-tag button-new-tag" size="small" @click="inputTagVisible = true"> + 添加时段限制 </el-button>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, watch } from 'vue'

const props = defineProps({
  timeRanges: {
    type: String,
    default: ''
  }
})
const emit = defineEmits<{
  (e: 'change', value: string[]): void
}>()
const _timeRanges = ref<string[]>([])
// 看两个数组是否完全相等
function arraysAreEqual<T>(a: T[], b: T[]): boolean {
  if (a.length !== b.length) {
    return false
  }
  return a.every((val, index) => val === b[index])
}
watch(
  () => props.timeRanges,
  (newTimeRanges) => {
    const newTimeRangesArr = newTimeRanges == null || newTimeRanges == '' ? [] : newTimeRanges.split(',').map((item) => item.trim())
    if (arraysAreEqual(newTimeRangesArr, _timeRanges.value)) return
    // 外部->内部
    _timeRanges.value = newTimeRangesArr
  },
  { immediate: true }
)
const inputTagVisible = ref(false)
const inputTimeRange = ref<[string, string]>(['', ''])

function removeTimeFromTimes(index: number) {
  _timeRanges.value.splice(index, 1)
  triggerChange()
}
function addTime() {
  if (inputTimeRange.value[0] == '' || inputTimeRange.value[1] == '') return
  _timeRanges.value.push(`${inputTimeRange.value[0]}-${inputTimeRange.value[1]}`)
  // 置空
  inputTimeRange.value[0] = ''
  inputTimeRange.value[1] = ''
  inputTagVisible.value = false
  triggerChange()
}
function triggerChange() {
  emit('change', _timeRanges.value)
}
</script>

<style scoped lang="scss">
.container {
  display: flex;
  flex-wrap: wrap;

  .time-picker-box {
    display: flex;
    margin-left: 5px;
    width: 160px;
  }

  .time-range-tag {
    margin: 5px 2px 0;
  }
}
</style>
